package cn.tang.tframe.common.base;

import cn.tang.tframe.common.utils.lang.StringUtils;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 配置文件装载器
 * 注意本地配置文件一般只存储初始化时需要的信息，
 * 不应该放置太多的配置信息（运行期可变的配置信息更不能放置在此），所以此类只支持一个配置文件
 * <p/>
 * 创建时间: 14-8-1 下午4:18<br/>
 *
 * @author tanghc
 * @since v0.0.1
 */
public class MainConfigLoader {
	public static final Logger logger = LoggerFactory.getLogger(MainConfigLoader.class);

	public static final String APP_MAINCONF_FILE = "config/main-conf.properties";
	public static final String LOCAL_MAINCONF_FILE = "/config/main-conf.properties";

	private static final String DEFAULT_CONFIG_FILE_KEY = "mainConfig";
	private static String CLIENT_CODE = null;
	private static class ConfigLoaderHolder{
		private static final MainConfigLoader instance = new MainConfigLoader();
	}

	private MainConfigLoader(){}

	private static Properties properties = null;
	static{
		properties = new Properties();
		InputStream is = null;
		try {
			String confFileName = System.getProperty(DEFAULT_CONFIG_FILE_KEY);
			//System.out.println(Thread.currentThread().getContextClassLoader().getResource(".").getPath());
			if(Strings.isNullOrEmpty(confFileName)) {//没有配置 从classloader获取

				if(is == null){
					try {
						File file = new File(LOCAL_MAINCONF_FILE);
						if(null != file && file.exists()){
							is = new FileInputStream(file);
						}
					} catch (Exception e) {
					}
				}
				if(null == is){
					is = Thread.currentThread().getContextClassLoader().getResourceAsStream(APP_MAINCONF_FILE);
				}
				properties.load(is);
			} else {
				is = new FileInputStream(new File(confFileName));
				properties.load(is);
			}
		} catch (IOException e) {
			logger.error("load properties {} error", DEFAULT_CONFIG_FILE_KEY, e);
			System.exit(-1);
		} finally {
			if(null != is){
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
	}


	/**
	 * 单例获取ConfigLoader
	 * @return
	 */
	public static MainConfigLoader getInstance(){
		return ConfigLoaderHolder.instance;
	}

	public String getProperty(String key){
		return properties.getProperty(key);
	}
	public String getDeployPath(){
		return getProperty("deployPath");
	}
	public String getDeployFile(){
		return getProperty("deployFile");
	}
	public String getZkUrl(){
		return getProperty("zkUrl");
	}
	public String getProductCode(){
		return getProperty("productCode");
	}
	public String getAppCode(){
		return getProperty("appCode");
	}
	public String getTmpFile(){
		return getProperty("tmpFile");
	}
	public String getClientCode(){
		if(StringUtils.isBlank(CLIENT_CODE)){
			CLIENT_CODE = new StringBuilder().append(getProductCode()).append("_").append(getAppCode()).toString();
		}
		return CLIENT_CODE;
	}


}
